//
//  EquipSettingVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/15.
//  Copyright © 2020 tym. All rights reserved.
//

#import "EquipSettingVC.h"
#import "Sizes.h"
#import "NSDate+HXExtension.h"
#import "NSDate+BRPickerView.h"
#import "IQKeyboardManager.h"
#import "EquipmentUserNameVC.h"
#import "BangFamilyUserVC.h"
#import "ShowAlertView.h"
#import "UIButton+Gradient.h"
#import "BRDatePickerView.h"
#import "AddOpenLockWayVC.h"
#import "WeekLoopView.h"
#import "UserProBtn.h"
#import "EquipmentService.h"
#import "UIButton+ImageTitleSpacing.h"
#import "UIView+ZFFrame.h"
@interface EquipSettingVC ()<UIScrollViewDelegate>


@property(nonatomic,weak) IBOutlet UIScrollView *scrollView;

@property(nonatomic,weak) IBOutlet UIView *topView;
@property(nonatomic,weak) IBOutlet UILabel *nameLab;
@property(nonatomic,weak) IBOutlet UITextField *nameFid;
@property(nonatomic,weak) IBOutlet UserProBtn *guanliBtn;
@property(nonatomic,weak) IBOutlet UserProBtn *putongBtn;
@property(nonatomic,weak) IBOutlet UserProBtn *bingkeBtn;
@property(nonatomic,weak) IBOutlet UserProBtn *xiepoBtn;
@property(nonatomic,weak) IBOutlet UIView *centerView;
@property(nonatomic,weak) IBOutlet UILabel *centerTitLab;
@property(nonatomic,weak) IBOutlet UIButton *allBtn;
@property(nonatomic,weak) IBOutlet UIButton *timeBtn;
@property(nonatomic,weak) IBOutlet UIButton *loopBtn;

@property(nonatomic,weak) IBOutlet UILabel  *startLab;
@property(nonatomic,weak) IBOutlet UILabel *endLab;
@property(nonatomic,weak) IBOutlet UILabel *weekShowLab;
@property(nonatomic,weak) IBOutlet UIView *startView;
@property(nonatomic,weak) IBOutlet UIView *endView;
@property(nonatomic,weak) IBOutlet UIView *loopView;

@property(nonatomic,strong) IBOutlet UIView *bottomView;
@property(nonatomic,weak) IBOutlet UILabel *userNameLab;
@property(nonatomic,weak) IBOutlet UIButton *deleBtn;
@property(nonatomic,weak) IBOutlet UIButton *saveBtn;

@property(nonatomic,assign) NSInteger  equipmentUserID;  //编辑时传入的设备用户ID 没有传就是新增指纹

@property(nonatomic,strong) EquipmentService *service;

@property(nonatomic,strong) EquipmentUserModel *equipUser;

@property(nonatomic,assign) NSInteger userRole;

@property(nonatomic,strong) NSString *weekStr;
@property(nonatomic,strong) NSString *addEffectiveTime;
@end

@implementation EquipSettingVC

-(instancetype)initWithEquipmentUserID:(NSInteger)userId{
    self = [super init];
    self.equipmentUserID = userId;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    self.scrollView.delegate = self;
    [self initUI];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [self getUserDetail];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

-(EquipmentService*)service{
    if (_service == nil) {
        _service = [[EquipmentService alloc] init];
    }
    return _service;
}

//获得设备用户的详情 
-(void)getUserDetail{
    if (!self.equipmentUserID) {
        return;
    }
    
    TYMWeak(self);
    [self.service getEquipmentusergetdetail:self.equipmentUserID completion:^(LMJBaseResponse * _Nonnull respons, EquipmentUserModel * _Nonnull userModel) {
        if (respons.message) {
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }else{
            weakself.equipUser = userModel;
            weakself.weekStr = userModel.validWeek;
            weakself.weekShowLab.text = [weakself getWeekStrWithstr:self.weekStr];

            [weakself updateUIFrame];
        }
    }];
}

-(void)updateUIFrame{
    
    self.topView.frame = CGRectMake(0, 0, ScreenWidth, self.topView.zf_height);
    [self.scrollView addSubview:self.topView];
    
    self.centerView.frame = CGRectMake(0, self.topView.zf_bottom, ScreenWidth, self.centerView.zf_height);
    [self.scrollView addSubview:self.centerView];
    
    if (self.equipUser) {
        if (self.equipUser.type == 3) {
            self.bottomView.frame = CGRectMake(0, self.centerView.zf_bottom, ScreenWidth, self.bottomView.zf_height);
            [self.scrollView addSubview:self.bottomView];
            self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.bottomView.zf_bottom);
        }
        self.nameFid.text = _equipUser.equipmentUserName;
        self.nameFid.userInteractionEnabled = NO;
        
        switch (self.equipUser.userRole) {
            case 1:
                self.userRole = 1;
                self.guanliBtn.selected = YES;
                self.putongBtn.selected = NO;
                self.bingkeBtn.selected = NO;
                self.xiepoBtn.selected = NO;
                break;
            case 0:
                self.userRole = 0;
                self.guanliBtn.selected = NO;
                self.putongBtn.selected = YES;
                self.bingkeBtn.selected = NO;
                self.xiepoBtn.selected = NO;
                break;
            case 2:
                self.userRole = 2;
                self.guanliBtn.selected = NO;
                self.putongBtn.selected = NO;
                self.bingkeBtn.selected = YES;
                self.xiepoBtn.selected = NO;
                break;
            case 3:
                self.userRole = 3;
                self.guanliBtn.selected = NO;
                self.putongBtn.selected = NO;
                self.bingkeBtn.selected = NO;
                self.xiepoBtn.selected = YES;
                break;
            default:
                break;
        }
        
        if (![self.equipUser.effectiveTime integerValue]) {
            [self changeAllOrTimeAction:self.allBtn];
        }else if([self.equipUser.effectiveTime integerValue] == 1){
            [self changeAllOrTimeAction:self.timeBtn];
            self.startLab.text = [self.equipUser.startTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
            self.endLab.text = [self.equipUser.endTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];;
        }else if([self.equipUser.effectiveTime integerValue] == 2){
            [self changeAllOrTimeAction:self.loopBtn];
            self.startLab.text = self.equipUser.start;
            self.endLab.text = self.equipUser.end;
        }
        self.bottomView.frame = CGRectMake(0, self.centerView.zf_bottom, ScreenWidth, self.bottomView.zf_height);
        [self.scrollView addSubview:self.bottomView];
        self.userNameLab.text = self.equipUser.userName;
    }else{
        self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.centerView.zf_bottom);
        self.nameFid.userInteractionEnabled = YES;
    }
    
    if ([self.equipUser.equipmentUserType isEqualToString:@"00"]) {
        [self addTitle:@"指纹设置"];
        self.nameLab.text = @"指纹命名";
        self.centerTitLab.text = @"指纹时效选择";
    }else if([self.equipUser.equipmentUserType isEqualToString:@"01"]){
        [self addTitle:@"卡设置"];
        self.nameLab.text = @"卡命名";
        self.centerTitLab.text = @"卡时效选择";
    }else if([self.equipUser.equipmentUserType isEqualToString:@"02"]){
        [self addTitle:@"密码设置"];
        self.nameLab.text = @"密码命名";
        self.centerTitLab.text = @"密码时效选择";
    }else if([self.equipUser.equipmentUserType isEqualToString:@"03"]){
        [self addTitle:@"遥控设置"];
        self.nameLab.text = @"遥控命名";
        self.centerTitLab.text = @"遥控时效选择";
    }
}

-(void)initUI{
    
    if (self.typeVC == 1 ) {
        [self addTitle:@"密码设置"];
        self.nameLab.text = @"密码命名";
        self.centerTitLab.text = @"密码时效选择";
        self.nameFid.placeholder = @"请输入密码名(选填)";
    }else if(self.typeVC == 2){
        [self addTitle:@"指纹设置"];
        self.nameLab.text = @"指纹命名";
        self.nameFid.placeholder = @"请输入指纹名(选填)";
        self.centerTitLab.text = @"指纹时效选择";
    }else if(self.typeVC == 3){
        self.nameFid.placeholder = @"请输入卡名(选填)";
        [self addTitle:@"卡设置"];
        self.nameLab.text = @"卡命名";
        self.centerTitLab.text = @"卡时效选择";
    }else if(self.typeVC ==4){
        self.nameFid.placeholder = @"请输入遥控名(选填)";
        self.nameLab.text = @"遥控命名";
        [self addTitle:@"遥控设置"];
        self.centerTitLab.text = @"遥控时效选择";
    }
    
    self.scrollView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavigateonHeight-SafeBottomMargin-74);
    self.topView.backgroundColor = viewBGColor;
    self.centerView.backgroundColor = viewBGColor;
    self.bottomView.backgroundColor = viewBGColor;
    self.saveBtn.layer.cornerRadius = 5;
    self.saveBtn.layer.masksToBounds = YES;
    self.deleBtn.layer.cornerRadius = 5;
    self.deleBtn.layer.masksToBounds = YES;
    self.deleBtn.layer.borderColor = rgba(151, 151, 151).CGColor;
    self.deleBtn.layer.borderWidth = 1;
    
    [self updateUIFrame];
    [self.allBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
    [self.timeBtn setImage:[UIImage imageNamed:@"icon_home12"] forState:UIControlStateNormal];
    [self.allBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:3];
    [self.timeBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:3];
    
    [self.loopBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
    [self.loopBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:3];
    
    if(self.equipmentUserID>0){
        self.deleBtn.hidden = NO;
    }else{
        self.weekStr = @"00000000";
        [self changeUserProAction:self.putongBtn];
        [self changeAllOrTimeAction:self.allBtn];
        self.deleBtn.hidden = YES;
        [self.saveBtn setTitle:@"确定添加" forState:UIControlStateNormal];
    }
    [self.saveBtn gradientButtonWithSize:self.saveBtn.bounds.size colorArray:@[(id)rgba(139, 175, 255),(id)rgba(76, 132, 255)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    
    
}

-(IBAction)changeUserProAction:(UIButton*)sender{
    
    switch (sender.tag) {
        case 1000:
            self.userRole = 1;
            self.equipUser.userRole = 1;
            self.guanliBtn.selected = YES;
            self.putongBtn.selected = NO;
            self.bingkeBtn.selected = NO;
            self.xiepoBtn.selected = NO;
            break;
        case 1001:
            self.userRole = 0;
            self.equipUser.userRole = 0;
            self.guanliBtn.selected = NO;
            self.putongBtn.selected = YES;
            self.bingkeBtn.selected = NO;
            self.xiepoBtn.selected = NO;
            break;
        case 1002:
            self.userRole = 2;
            self.equipUser.userRole = 2;
            self.guanliBtn.selected = NO;
            self.putongBtn.selected = NO;
            self.bingkeBtn.selected = YES;
            self.xiepoBtn.selected = NO;
            break;
        case 1003:
            self.userRole = 3;
            self.equipUser.userRole = 3;
            self.guanliBtn.selected = NO;
            self.putongBtn.selected = NO;
            self.bingkeBtn.selected = NO;
            self.xiepoBtn.selected = YES;
            break;
        default:
            break;
    }
    
}

//指纹时效
-(IBAction)changeAllOrTimeAction:(UIButton*)sender{
    
    if(sender.tag == 100){
        self.equipUser.effectiveTime = @"00";
        self.addEffectiveTime = @"00";
        [self.allBtn setImage:[UIImage imageNamed:@"icon_home12"] forState:UIControlStateNormal];
        [self.timeBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
        [self.loopBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
        self.startView.hidden = YES;
        self.endView.hidden = YES;
        self.loopView.hidden = YES;
        self.centerView.frame = CGRectMake(0, self.topView.zf_bottom, ScreenWidth, 118);
    }else if(sender.tag == 101) {
        self.equipUser.effectiveTime = @"01";
        self.addEffectiveTime = @"01";
        if(self.equipUser){
            self.startLab.text= [self.equipUser.startTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
            self.endLab.text = [self.equipUser.endTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];;
        }else{
            self.startLab.text = @"请选择开始时间";
            self.endLab.text = @"请选择结束时间";
        }
        
        self.loopView.hidden = YES;
        self.startView.hidden = NO;
        self.endView.hidden = NO;
        [self.allBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
        [self.timeBtn setImage:[UIImage imageNamed:@"icon_home12"] forState:UIControlStateNormal];
        [self.loopBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
        self.centerView.frame = CGRectMake(0, self.topView.zf_bottom, ScreenWidth, 226);
        
        if (!self.equipUser.startTime) {
            [self startTimeAction:nil]; //开始时间
        }
    }else if(sender.tag == 102){
        self.equipUser.effectiveTime = @"02";
        self.addEffectiveTime = @"02";
        self.startLab.text = @"00:00:00";
        self.endLab.text = @"23:59:59";
        self.loopView.hidden = NO;
        self.startView.hidden = NO;
        self.endView.hidden = NO;
        [self.allBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
        [self.timeBtn setImage:[UIImage imageNamed:@"icon_home13"] forState:UIControlStateNormal];
        [self.loopBtn setImage:[UIImage imageNamed:@"icon_home12"] forState:UIControlStateNormal];
        self.centerView.frame = CGRectMake(0, self.topView.zf_bottom, ScreenWidth, 285);
    }
    [self.scrollView addSubview:self.centerView];
    
    if (self.equipUser) {
        self.bottomView.frame = CGRectMake(0, self.centerView.zf_bottom, ScreenWidth, self.bottomView.zf_height);
        [self.scrollView addSubview:self.bottomView];
        self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.bottomView.zf_bottom);
    }
    
}

//设置开始时间
-(IBAction)startTimeAction:(id)sender{
    
    // 1.创建日期选择器
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    // 2.设置属性
    if ([self.equipUser.effectiveTime isEqualToString:@"01"] || [self.addEffectiveTime isEqualToString:@"01"]) {
        datePickerView.pickerMode = BRDatePickerModeYMDHMS;
        datePickerView.minDate = [NSDate date];
        NSDate *data = [NSDate new];
        datePickerView.selectDate = [NSDate br_setYear:data.br_year month:data.br_month day:data.br_day];
    }else if ([self.equipUser.effectiveTime isEqualToString:@"02"]|| [self.addEffectiveTime isEqualToString:@"02"]) {
        datePickerView.pickerMode = BRDatePickerModeHMS;
    }
    datePickerView.title = @"选择开始时间";
    datePickerView.isAutoSelect = NO;
    TYMWeak(self);
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        weakself.startLab.text = selectValue;
        [weakself endTimeAction:nil];
    };
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.topCornerRadius = 10;
    customStyle.pickerTextColor = rgba(51, 51, 51);
    customStyle.separatorColor = rgba(234, 234, 234);
    customStyle.cancelTextColor = rgba(102, 102, 102);
    customStyle.doneTextColor = rgba(51, 51, 51);
    customStyle.hiddenTitleLine = YES;
    customStyle.rowHeight = 42;
    customStyle.pickerHeight = 225;
    customStyle.cancelTextFont = Font_Regular(15);
    customStyle.doneTextFont  = Font_Regular(15);
    customStyle.pickerTextFont = Font_Regular(22);
    datePickerView.pickerStyle = customStyle;
    [datePickerView show];
}

//设置结束时间
-(IBAction)endTimeAction:(id)sender{
    
    // 1.创建日期选择器
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    // 2.设置属性
    if ([self.equipUser.effectiveTime isEqualToString:@"01"] || [self.addEffectiveTime isEqualToString:@"01"]) {
        datePickerView.pickerMode = BRDatePickerModeYMDHMS;
        datePickerView.minDate = [NSDate date];
    }else if ([self.equipUser.effectiveTime isEqualToString:@"02"]|| [self.addEffectiveTime isEqualToString:@"02"]) {
        datePickerView.pickerMode = BRDatePickerModeHMS;
    }
    datePickerView.title = @"选择结束时间";
    NSDate *data = [NSDate new];
    datePickerView.selectDate = [NSDate br_setYear:data.br_year month:data.br_month day:data.br_day];
    datePickerView.isAutoSelect = NO;
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        self.endLab.text = selectValue;
    };
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.topCornerRadius = 10;
    customStyle.pickerTextColor = rgba(51, 51, 51);
    customStyle.separatorColor = rgba(234, 234, 234);
    customStyle.cancelTextColor = rgba(102, 102, 102);
    customStyle.doneTextColor = rgba(51, 51, 51);
    customStyle.hiddenTitleLine = YES;
    customStyle.rowHeight = 42;
    customStyle.pickerHeight = 225;
    customStyle.cancelTextFont = Font_Regular(15);
    customStyle.doneTextFont  = Font_Regular(15);
    customStyle.pickerTextFont = Font_Regular(22);
    datePickerView.pickerStyle = customStyle;
    [datePickerView show];
}

//获取要展示的周循环
-(NSString*)getWeekStrWithstr:(NSString*)weekStr{
    if (weekStr.length > 7) {
        weekStr = [weekStr substringFromIndex:1];
    }
    
    NSString *returnStr=@"";
    if ([weekStr isEqualToString:@"11111111"]) {
        return @"每天";
    }else{
        returnStr=@"每周";
        NSString *weekStrS=@"";
        NSArray *week = @[@"日",@"六",@"五",@"四",@"三",@"二",@"一"];
        for(int i=0;i<week.count;i++){
            NSString *numStr = [weekStr substringWithRange:NSMakeRange(i, 1)];
            if ([numStr integerValue]){
                weekStrS = [weekStrS stringByAppendingString:week[i]];
                weekStrS = [weekStrS stringByAppendingString:@","];
            }
        }
        if (weekStrS.length) {
            weekStrS = [weekStrS substringToIndex:weekStrS.length-1];
            weekStrS = [self reversalString:weekStrS];
            return [returnStr stringByAppendingString:weekStrS];
        }
    }
    return @"";
}

//字符串反转
- (NSString *)reversalString:(NSString *)originString{
    NSString *resultStr = @"";
    for (NSInteger i = originString.length -1; i >= 0; i--) {
      NSString *indexStr = [originString substringWithRange:NSMakeRange(i, 1)];
      resultStr = [resultStr stringByAppendingString:indexStr];
    }
  return resultStr;
}


//选择周循环
-(IBAction)selectWeekLoop:(id)sender{
    
    WeekLoopView *pop = [[WeekLoopView alloc]initWithFrame:self.view.frame];
    if (self.weekStr.length > 7) {
        self.weekStr = [self.weekStr substringFromIndex:1];
    }
    [pop setSeleStr:self.weekStr];
    
    pop.blockCallBackIndex = ^(NSString *str,NSString *showStr) {
        self.weekStr = [NSString stringWithFormat:@"%@%@",@"0",str];
        self.weekShowLab.text = [self getWeekStrWithstr:self.weekStr];
    };
    [pop viewShow];
}

-(IBAction)changeEquipmentUserName:(id)sender{

    if (!_equipmentUserID) {
        return;
    }
    
    EquipmentUserNameVC *nameVC = [[EquipmentUserNameVC alloc] init];
    nameVC.equipMentID = self.equipmentUserID;
    nameVC.nameStr = self.equipUser.equipmentUserName;
    nameVC.titleStr = [[self.nameLab.text substringToIndex:self.nameLab.text.length-2] stringByAppendingString:@"名称"];
    [self.navigationController pushViewController:nameVC animated:YES];
    
}

-(IBAction)seleUserAction:(id)sender{
    
    BangFamilyUserVC *bangVC = [[BangFamilyUserVC alloc] init];
    bangVC.type = 0;
    bangVC.equipmentUserID = self.equipmentUserID;
    bangVC.equipmentID = self.equipUser.equipmentId;
    [self.navigationController pushViewController:bangVC animated:YES];
}

//删除指纹用户
-(IBAction)deletePassword:(id)sender{
    
    NSString *message = [NSString stringWithFormat:@"确定删除该%@吗?",[self.nameLab.text substringToIndex:self.nameLab.text.length-2]];
    TYMWeak(self);
    [ShowAlertView showAlertViewTitle:@"提示" message:message actionBtnTitle:@"确定" hiddenCancel:NO completion:^(NSInteger actionType) {
        if (actionType) {
            [weakself deleteUser];
        }
    }];
}

-(void)deleteUser{
    TYMWeak(self);
    [self.service getEquipmentdeleteuserlockEpumentId:_equipUser.equipmentId equipmentUserIDs: [ NSString stringWithFormat:@"%ld", _equipUser.equipmentUserId] completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.message) {
            [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                   hiddenCancel:NO
                                   completion:^(NSInteger actionType) {
                if (actionType) {
                    if (respons.code == 2001) {
                        [weakself getDeleteVerifyAdminrole:self.equipUser];
                    }
                }
            }];
        }else{
            [weakself.navigationController popViewControllerAnimated:YES];
        }
    }];
}

//保存指纹用户
-(IBAction)saveAction:(id)sender{
    //周循环
    if ([self.addEffectiveTime isEqualToString:@"02"] && [self.weekShowLab.text isEqualToString:@""]) {
        [WHToast showMessage:@"请选择循环时间" duration:2 finishHandler:nil];
        return;
    }
    
    //有效期
    if ([self.addEffectiveTime isEqualToString:@"01"]) {
        if (self.startLab.text.length == 0 || [self.startLab.text isEqualToString:@"请选择开始时间"]) {
            [WHToast showMessage:@"输入的参数不合法" duration:2 finishHandler:nil];
            return;
        }
        if (self.endLab.text.length == 0 || [self.endLab.text isEqualToString:@"请选择结束时间"]) {
            [WHToast showMessage:@"输入的参数不合法" duration:2 finishHandler:nil];
            return;
        }
    }
    
    if (_equipmentUserID) {
        
        if (self.oldEquUser.userRole != self.equipUser.userRole || ![self.oldEquUser.effectiveTime isEqualToString: self.equipUser.effectiveTime]) { //肯定修改了
            [self saveEquipmentUser];
        }else{
            if ([self.equipUser.effectiveTime isEqualToString:self.oldEquUser.effectiveTime]) { //时效修改了
                
                if ([self.equipUser.effectiveTime isEqualToString:@"01"]) {
                    if (![[self.oldEquUser.startTime stringByReplacingOccurrencesOfString:@"T" withString:@" "] isEqualToString:self.startLab.text] || ![[self.oldEquUser.endTime stringByReplacingOccurrencesOfString:@"T" withString:@" "] isEqualToString:self.endLab.text]) {
                        [self saveEquipmentUser];
                    }else{
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }else if([self.equipUser.effectiveTime isEqualToString:@"02"]){
                    if (![self.oldEquUser.start isEqualToString:self.startLab.text] || ![self.oldEquUser.endTime isEqualToString:self.endLab.text]) {
                        [self saveEquipmentUser];
                    }else{
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }else{
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }else{  //新增
        
        if ([self checkTime]) {
            [WHToast showMessage:@"开始时间要早于结束时间" duration:2 finishHandler:nil];
            return;
        }
        
        EquipmentUserModel *model = [[EquipmentUserModel alloc] init];
        model.equipmentUserName = _nameFid.text;
        model.effectiveTime = self.addEffectiveTime;
        model.userRole = self.userRole;
        model.startTime = self.startLab.text;
        model.endTime = self.endLab.text;
        model.start = self.startLab.text;
        model.end = self.endLab.text;
        model.validWeek = self.weekStr;
        model.equipmentId = self.equipMentID;
        model.equipmentUserId  = self.userId;
        model.type = self.type ;
        
        if (self.typeVC == 1) {
            model.equipmentUserType = @"02";
        }else if(self.typeVC == 2){
            model.equipmentUserType = @"00";
        }else if(self.typeVC == 3){
            model.equipmentUserType = @"01";
        }else if(self.typeVC == 4){
            model.equipmentUserType = @"03";
        }
        
        //新增设备用户
        [self addEquipmentUser:model];
    }
}

-(BOOL)checkTime{
    
    if ([_addEffectiveTime isEqualToString:@"01"] ) {
        NSDate *starDate = [NSDate br_getDate:self.startLab.text format:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *endDate = [NSDate br_getDate:self.endLab.text format:@"yyyy-MM-dd HH:mm:ss"];
        
        
        
        
        if ([starDate br_compare:endDate format:@"yyyy-MM-dd HH:mm:ss"] == NSOrderedDescending) {
            return YES;
        }
        return NO;
    }
    return NO;
}

-(void)saveEquipmentUser{
    
    if ([self checkTime]) {
        [WHToast showMessage:@"开始时间要早于结束时间" duration:2 finishHandler:nil];
        return;
    }
    TYMWeak(self);
    [self.service getEquipmentUpdateuserlockpmentId:_equipUser.equipmentId effectiveTime:self.equipUser.effectiveTime userRole:self.equipUser.userRole startTime:![self.startLab.text isEqualToString:@"请选择开始时间"]?self.startLab.text:@""   endTime:![self.endLab.text isEqualToString:@"请选择结束时间"]?self.endLab.text:@"" validWeek:self.weekStr equipmentUserAuthId:_equipmentUserID
                                               star:![self.startLab.text isEqualToString:@"请选择开始时间"]?self.startLab.text:@"" end:![self.endLab.text isEqualToString:@"请选择结束时间"]?self.endLab.text:@"" equipmentUserName:self.nameFid.text completion:^(LMJBaseResponse * _Nonnull respons) {
        
        if (respons.code == 0) {
            [WHToast showMessage:@"保存成功" duration:2 finishHandler:^{
                [weakself.navigationController popViewControllerAnimated:YES];
            }];
        }else {
            [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                   hiddenCancel:NO
                                   completion:^(NSInteger actionType) {
                if (actionType) {
                    if (respons.code == 2001) {
                        [weakself getVerifyAdminrole:self.equipUser];
                    }
                }
            }];
        }
    }];
}

-(void)addEquipmentUser:(EquipmentUserModel*)equipUserModel{
    
    TYMWeak(self);
    [self.service getEquipmentAdduserlockequipmentId:equipUserModel.equipmentId equipmentUserType:equipUserModel.equipmentUserType effectiveTime:equipUserModel.effectiveTime userRole:equipUserModel.userRole startTime:equipUserModel.startTime endTime:equipUserModel.endTime
                                               start:equipUserModel.start
                                                 end:equipUserModel.end validWeek:equipUserModel.validWeek type:equipUserModel.type userId:equipUserModel.equipmentUserId
                                                name:self.nameFid.text completion:^(LMJBaseResponse * _Nonnull respons) {
        
        if (respons.code == 0) {
            AddOpenLockWayVC *lockVC = [[AddOpenLockWayVC alloc] init];
            lockVC.equipUserModel = equipUserModel;
            [self.navigationController pushViewController:lockVC animated:YES];
        }else {
            if (self.typeVC  == 4) {
                [WHToast showMessage:@"暂不支持添加遥控" duration:2 finishHandler:nil];
            }else{
                [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                       hiddenCancel:NO
                                       completion:^(NSInteger actionType) {
                    if (actionType) {
                        if (respons.code == 2001) {
                            [weakself getVerifyAdminrole:equipUserModel];
                        }
                    }
                }];
            }
        }
    }];
}

//验证管理员
-(void)getVerifyAdminrole:(EquipmentUserModel*)equipUserModel{
    TYMWeak(self);
    [self.service getVerifyadminroleEpumentId:equipUserModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            [weakself saveAction:nil];
        }else{
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }
    }];
}

-(void)getDeleteVerifyAdminrole:(EquipmentUserModel*)equipUserModel{
    TYMWeak(self);
    [self.service getVerifyadminroleEpumentId:equipUserModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            [weakself deleteUser];
        }else{
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }
    }];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.nameFid resignFirstResponder];
}

@end
